package juc.flowcontrol.condition;

import java.util.PriorityQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author fangbin
 * @desc
 * @date 2020/6/26 20:13
 */
public class ConditionDemo2 {
    private int queueSize = 10;

    private PriorityQueue<Integer> queue = new PriorityQueue<>(queueSize);

    private Lock lock = new ReentrantLock();
    Condition full = lock.newCondition();
    Condition empty = lock.newCondition();

    public static void main(String[] args) {
        ConditionDemo2 conditionDemo2 = new ConditionDemo2();

        Product product = conditionDemo2.new Product();
        Consumer consumer = conditionDemo2.new Consumer();
        product.start();
        consumer.start();


    }
      class Product extends Thread{
        @Override
        public void run() {

            while (true){
                lock.lock();
                try{
                    while (queue.size()==queueSize){
                        System.out.println("队列满，等待有空余");
                        try {
                            full.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.offer(1);
                    System.out.println("向队列插入一个元素，队列大小"+queue.size());
                    empty.signal();
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    class Consumer extends Thread{
        @Override
        public void run() {
            while (true){
                lock.lock();
                try{
                    while (queue.size()==0){
                        System.out.println("队列为空");
                        try {
                            empty.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.poll();
                    System.out.println("向队列取出一个元素，队列大小"+queue.size());
                    full.signal();
                }finally {
                    lock.unlock();
                }
            }
        }
    }
}
